import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { HttpExceptionsFilter } from './common/filters/http-exceptions-filter';
import { ValidationPipe } from '@nestjs/common';
import rateLimit from 'express-rate-limit';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { knife4jSetup } from 'nest-knife4j2';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    cors: true, // 开启跨域访问
  });

  // 获取配置
  const config = app.get(ConfigService);

  // 设置访问频率
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15 分钟
      max: 1000, // 限制15分钟内最多只能访问1000次
    }),
  );

  // 设置 api 访问前缀
  const prefix = config.get<string>('app.prefix');
  app.setGlobalPrefix(prefix);

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionsFilter());

  // 全局管道(用于整个应用程序中的每个路由处理器)
  app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));

  // 配置接口文档工具
  // 1. 配置swagger
  const swaggerOptions = new DocumentBuilder().setTitle('Nest-RuoYi').setDescription('接口文档').setVersion('1.0.0').addBearerAuth().build();
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  SwaggerModule.setup(`${prefix}/swagger-ui`, app, document, {
    swaggerOptions: {
      persistAuthorization: true,
    },
    customSiteTitle: 'Nest-RuoYi API Docs',
  });
  // 2. 配置knif4j
  knife4jSetup(app, {
    urls: [
      {
        name: 'Nest-RuoYi',
        url: `/swagger-ui-json`,
        swaggerVersion: '1.0.0',
        location: `/swagger-ui-json`,
      },
    ],
  });

  // 读取配置中服务端口
  const port = config.get<number>('app.port') || 8080;
  await app.listen(port);

  console.log(`Nest-RuoYi 服务启动成功 `, '\n', '\n', '服务地址', `http://localhost:${port}${prefix}/`, '\n', 'swagger文档地址', `http://localhost:${port}${prefix}/swagger-ui/`);
}
bootstrap();
